﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IDAL;
using ZSZ.IService;
using ZSZ.Model;

namespace ZSZ.Service
{
    public partial class AdminUserRoleService : BaseService<AdminUserRole>, IAdminUserRoleService
    {
        /// <summary>
        /// 给角色roleId增加权限项id permIds
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="permIds"></param>
        public void AddRoleIds(long adminId, long[] roleIds)
        {
            //管理员是否存在
            AdminUser user = DbSession.AdminUserDal.GetById(adminId);
            if (user == null)
            {
                throw new ArgumentException("管理员不存在" + adminId);
            }

            if (roleIds == null)
            {
                return;
                //throw new ArgumentException("未设置管理员" + adminId + "角色");
            }

            //角色是否存在
            //var roles = RoleDal.GetAll().Where(r => roleIds.Contains(r.Id)).ToArray();
            var roles = DbSession.RoleDal.GetAll().Where(r => roleIds.Contains(r.Id)).ToArray();
            foreach (var role in roles)
            {
                AdminUserRole ar = new AdminUserRole();
                ar.AdminUserId = user.Id;
                ar.RoleId = role.Id;
                ar.IsDeleted = false;
                ar.CreateDateTime = DateTime.Now;
                CurrentDal.Add(ar);
            }
            DbSession.SaveChanges();
        }

        public void UpdateRoleIds(long adminId, long[] roleIds)
        {
            //管理员是否存在
            AdminUser user = DbSession.AdminUserDal.GetById(adminId);
            if (user == null)
            {
                throw new ArgumentException("管理员不存在" + adminId);
            }

            if (roleIds == null)
            {
                return;
                //throw new ArgumentException("未设置管理员" + adminId + "角色");
            }

            //删除旧权限
            //user.AdminUserRoles.Clear();
            var adminUserRole = CurrentDal.GetAll().Where(ar => ar.AdminUserId == adminId);
            foreach (var ar in adminUserRole)
            {
                BatchDeleted(ar);
            }

            //角色是否存在
            var roles = DbSession.RoleDal.GetAll().Where(r => roleIds.Contains(r.Id)).ToArray();
            foreach (var role in roles)
            {
                AdminUserRole ar = new AdminUserRole();
                ar.AdminUserId = user.Id;
                ar.RoleId = role.Id;
                ar.IsDeleted = false;
                ar.CreateDateTime = DateTime.Now;
                CurrentDal.Add(ar);
            }
            DbSession.SaveChanges();
        }
    }
}
